package com.algorithm;

/**
 * 岛屿的数量(深度优先搜索)
 */
public class NumberOfIslands {

    public static int numIslands(char[][] grid) {
        int count = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == '1') {
                    count++;
                    sink(i, j, grid);
                }
            }
        }
        return count;
    }

    private static void sink(int i, int j, char[][] grid) {
        grid[i][j] = '0';
        if (i - 1 >= 0 && grid[i - 1][j] == '1') {
            sink(i - 1, j, grid);
        }
        if (j - 1 >= 0 && grid[i][j - 1] == '1') {
            sink(i, j - 1, grid);
        }
        if (i + 1 < grid.length && grid[i + 1][j] == '1') {
            sink(i + 1, j, grid);
        }
        if (j + 1 < grid[0].length && grid[i][j + 1] == '1') {
            sink(i, j + 1, grid);
        }
    }

    public static void main(String[] args) {
        char nums[][] =
//                {
//                {'1', '1', '1', '1', '0'},
//                {'1', '1', '0', '1', '0'},
//                {'1', '1', '0', '0', '0'},
//                {'0', '0', '0', '0', '0'}
//        };
                       {{'1','1','1'},
                        {'0','1','0'},
                        {'1','1','1'}};
        int result = numIslands(nums);
        System.out.println(result);
    }
}
